package cn.tworice.blog.utils;

import lombok.extern.slf4j.Slf4j;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

// UDP相关工具类
@Slf4j
public class UdpUtil {

    /**
     * 给指定地址发送UDP消息
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public void sendMessage(String host,Integer port,Object message){
        DatagramSocket datagramSocket = null;

        try {
            // 建立Socket
            datagramSocket = new DatagramSocket();
            // 创建包
            String data = message.toString();
            DatagramPacket datagramPacket = new DatagramPacket(data.getBytes(StandardCharsets.UTF_8), data.length());
            // 设置接收的地址
            datagramPacket.setAddress(InetAddress.getByName(host));
            // 设置接收的端口
            datagramPacket.setPort(port);
            // 发送包
            datagramSocket.send(datagramPacket);
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("发送UDP消息报错");
        }finally {
            // 关闭数据流
            datagramSocket.close();
        }
    }

    /**
     * 接收UDP消息
     * @author 二饭
     * @email 1786705138@qq.com
     */
    public void receive(Integer port){
        DatagramSocket datagramSocket = null;
        try {
            // 建立Socket
            datagramSocket = new DatagramSocket(port);

            // 接收数据包
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
            datagramSocket.receive(packet);
            System.out.println("接收来自IP地址："+packet.getAddress().getHostAddress());
            System.out.println("消息内容如下:"+new String(packet.getData(),0,packet.getLength()));

        } catch (Exception exception) {
            exception.printStackTrace();
            log.error("接收UDP消息报错");
        }
    }
}
